package com.xiaohutech.tanmiao

import androidx.lifecycle.lifecycleScope
import com.xiaohutech.tanmiao.databinding.ActivityWelcomeBinding
import com.xiaohutech.tanmiao.ui.dialog.AppProtocolDialog
import com.xiaohutech.tm.home.HomeActivity
import com.yxh.lib_base.base.BaseActivity
import com.yxh.lib_base.ext.lazyNone
import com.yxh.lib_base.ext.view.buildSpannableString
import com.yxh.lib_base.ext.view.visibleOrGone
import com.yxh.lib_base.ext.viewbinding.binding
import com.yxh.lib_base.util.router.navigationToAc
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

class WelcomeActivity : BaseActivity() {

    override val mBinding by binding<ActivityWelcomeBinding>()

    private val mProtocolHelp by lazyNone { AppProtocolDialog(this) }

    override fun onCreated() {
        mProtocolHelp.checkProtocol {
            if (!it){
                return@checkProtocol
            }
            onCountdown()
        }
    }

    private fun onCountdown() {
        val time = 1
        countDownCoroutines(time, lifecycleScope, onStart = {
            mBinding.welcomeNum.visibleOrGone(true)?.buildSpannableString {
                addText("点击跳转 ${time}s")
            }
        }, onTick = {
            runOnUiThread {
                mBinding.welcomeNum.buildSpannableString {
                    addText("点击跳转")
                    if (it > 0) {
                        addText(" ${it}s")
                    }
                }
            }
        }, onFinish = {
            navigationToAc(HomeActivity::class.java.simpleName)
            finish()
        })
    }

    private fun countDownCoroutines(
        total: Int, scope: CoroutineScope,
        onTick: (Int) -> Unit,
        onStart: (() -> Unit)? = null,
        onFinish: (() -> Unit)? = null,
    ): Job {
        return flow {
            for (i in total downTo 0) {
                emit(i)
                delay(1000)
            }
        }.flowOn(Dispatchers.Main)
            .onStart { onStart?.invoke() }
            .onCompletion { onFinish?.invoke() }
            .onEach { onTick.invoke(it) }
            .launchIn(scope)
    }


}